package com.simple.util.thread;

import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.FutureTask;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @program: simple_tools
 * @description: 线程工厂
 * @author: Mr.chen
 * @create: 2020-06-08 15:51
 **/
public class ThreadFactory {

    private static ExecutorService executorService = null;
    static {
        if (executorService == null) {
            // 创建等待队列
            BlockingQueue<Runnable> bqueue = new LinkedBlockingQueue<Runnable>();
            int threadNum = Runtime.getRuntime().availableProcessors() * 2;
            executorService = new ThreadPoolExecutor(threadNum, threadNum, 10L, TimeUnit.MILLISECONDS, bqueue);
        }
    }

    /**
     * 添加线程池任务
     *
     * @param run
     */
    public static synchronized <V> V addTask(Callable<V> run) {
        FutureTask<V> futureTask = new FutureTask<V>(run);
        try {
            executorService.submit(futureTask);

            V result = futureTask.get();
            return result;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 添加线程池任务
     *
     * @param runs
     */
    public static synchronized <V> void addsTask(List<Callable<V>> runs) {
        if (runs != null && runs.size() > 0) {
            for (Callable<V> r : runs) {
                addTask(r);
            }
        }
    }

    /**
     * 关闭线程池
     */
    public void closePool() {
        executorService.shutdown();
    }
}
